package cn.lcfms.cms;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import cn.lcfms.app.admin.bean.CollectBean;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class Collect{
	private static Logger logger = Logger.getLogger(Collect.class); 	
	//0停止，1启动，2暂停
	private int status=0;
	private boolean success;
	private String msg;	
	private String nowUrl;	
	private int num=0;
	private CollectBean bean;
	

	private Collect() {}
	private static Collect collect=null;
	public synchronized static Collect getColl() {
		if(collect==null) {
			collect=new Collect();
		}
		return collect;
	}	
	
	public CollectBean getBean() {
		return bean;
	}

	public void setBean(CollectBean bean) {
		this.bean = bean;
	}
	
	public String getNowUrl() {
		return nowUrl;
	}

	public String getMsg() {
		return msg;
	}

	public int getStatus() {
		return status;
	}
	
	public void setSuccess(boolean success) {
		this.success = success;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public void stop() {
		status=0;
		CollctBase.clearUrl();
		logger.info("采集已经停止");
	}
	
	public void start() {
		status=1;
		Timer timer=new Timer();
		timer.schedule(new TimerTask() {
			@Override
			public void run() {
				CollctBase.update(Collect.this);
			}
		}, 100);
		logger.info("采集已经启动");
	}
	
	public void pause() {
		status=2;
		logger.info("采集已经暂停");
	}
	
	public boolean isSuccess() {
		return success;
	}

	public int getNum() {
		return num;
	}
	
	public boolean loopCollct() {
		type_2_3();
		if(status==1) {
			return true;
		}
		return false;
	}
	
	private void type_2_3() {
		String stackUrl = CollctBase.getStackUrl();
		if(stackUrl==null) {
			return;
		}
		String content;
		try {
			logger.info("获取："+stackUrl);
			nowUrl=stackUrl;
			byte[] b = CollctBase.browser(stackUrl,bean.getCookie());
			if(bean.getType()==1) {
				CollctBase.getPageA(stackUrl, bean.getCookie(), bean.getCharset(), bean.getPreg());
			}
			content=new String(b,bean.getCharset());
			if(content==null || content.equals("")) {
				this.success=false;
				this.msg=nowUrl+"，返回的内容为空";
				return;
			}
		} catch (IOException e) {
			this.success=false;
			this.msg=nowUrl+"，IO异常，连接请求失败";
			return;
		}
		parseContent(content);
	}
	
	//处理内容
	private void parseContent(String content) {
		HashMap<String, String> map=new HashMap<>();
		Document doc = Jsoup.parse(content);
		JSONArray property = JSONArray.fromObject(bean.getProperty());
		for(int i=0;i<property.size();i++) {
			JSONObject object = property.getJSONObject(i);
			String pkey=object.getString("pkey");
			String pvalue=object.getString("pvalue");
			if(pvalue.startsWith("/") && pvalue.endsWith("/")) {
				pvalue=pvalue.substring(1, pvalue.length()-1).trim();
				Elements e = doc.select(pvalue);
				String html = e.html();
				if(html!=null && !html.equals("")) {
					map.put(pkey, html);
				}
			}else {
				map.put(pkey, pvalue);
			}				
		}
		try {
			String impl=bean.getImpl().substring(0, bean.getImpl().indexOf(".class"));
			Class<?> cl=Class.forName("cn.lcfms.cms.collect."+impl);
			Constructor<?> constructor = cl.getConstructor(Collect.class);
			CollectResult result=(CollectResult) constructor.newInstance(this);
			try {
				boolean _do = result._do(map);
				if(_do) {
					num++;
				}
			} catch (Exception e) {
				return;
			}		
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}	
}